use regex::Regex;

pub fn convert_base(input: &str, to_base: u32) -> String {
    assert!(to_base >= 2 && to_base <= 16, "Base must be between 2 and 16");

    let re = Regex::new(r"^([0-9A-Fa-f]+)\((\d+)\)$").unwrap();
    if let Some(captures) = re.captures(input) {
        let num_str = &captures[1]; // 数字部分
        let from_base: u32 = captures[2].parse().unwrap_or(0);

        if from_base < 2 || from_base > 16 {
            return "Base must be between 2 and 16".to_string();
        }

        let valid_re = Regex::new(&format!("^[0-{}]+$", if from_base <= 10 { from_base - 1 } else { 9 + ('A' as u32 - '0' as u32 + from_base - 10) as u32 })).unwrap();
        if !valid_re.is_match(num_str) {
            return "Wrong".to_string();
        }

        let decimal_value = match u64::from_str_radix(num_str, from_base) {
            Ok(value) => value,
            Err(_) => return "Wrong".to_string(),
        };

        let mut result = String::new();
        let mut num = decimal_value;

        if num == 0 {
            return "0".to_string();
        }

        while num > 0 {
            let digit = (num % to_base as u64) as u8;
            let digit_char = if digit < 10 {
                (digit + b'0') as char
            } else {
                (digit - 10 + b'a') as char
            };
            result.push(digit_char);
            num /= to_base as u64;
        }

        let reversed_result: String = result.chars().rev().collect();
        return reversed_result;
    } else {
        return "Wrong".to_string();
    }
}
